import { SafeTimer, SafeDelay } from './safeTimers'

// 离线语音识别备选方案
export interface OfflineSpeechOptions {
  language: string
  continuous: boolean
  interimResults: boolean
}

export class OfflineSpeechRecognition {
  private static instance: OfflineSpeechRecognition | null = null
  private isSupported = false
  private recognition: any = null

  constructor() {
    this.checkSupport()
  }

  static getInstance(): OfflineSpeechRecognition {
    if (!this.instance) {
      this.instance = new OfflineSpeechRecognition()
    }
    return this.instance
  }

  private checkSupport(): void {
    // 检查浏览器是否支持Web Speech API
    const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition
    this.isSupported = !!SpeechRecognition
  }

  isAvailable(): boolean {
    return this.isSupported
  }

  // 创建语音识别实例
  createRecognition(options: OfflineSpeechOptions) {
    if (!this.isSupported) {
      throw new Error('浏览器不支持语音识别')
    }

    const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition
    this.recognition = new SpeechRecognition()

    // 配置识别参数
    this.recognition.continuous = options.continuous
    this.recognition.interimResults = options.interimResults
    this.recognition.lang = options.language
    this.recognition.maxAlternatives = 1

    return this.recognition
  }

  // 获取支持的语言列表
  getSupportedLanguages(): string[] {
    return [
      'zh-CN', // 中文（简体）
      'zh-TW', // 中文（繁体）
      'en-US', // 英语（美国）
      'en-GB', // 英语（英国）
      'ja-JP', // 日语
      'ko-KR', // 韩语
      'fr-FR', // 法语
      'de-DE', // 德语
      'es-ES', // 西班牙语
      'it-IT', // 意大利语
      'pt-BR', // 葡萄牙语（巴西）
      'ru-RU', // 俄语
    ]
  }

  // 检查特定语言是否支持
  isLanguageSupported(language: string): boolean {
    return this.getSupportedLanguages().includes(language)
  }

  // 获取浏览器信息
  getBrowserInfo(): { name: string; version: string; supported: boolean } {
    const userAgent = navigator.userAgent
    let name = 'Unknown'
    let version = 'Unknown'
    let supported = false

    if (userAgent.includes('Chrome')) {
      name = 'Chrome'
      const match = userAgent.match(/Chrome\/(\d+)/)
      version = match ? match[1] : 'Unknown'
      supported = true
    } else if (userAgent.includes('Safari') && !userAgent.includes('Chrome')) {
      name = 'Safari'
      const match = userAgent.match(/Version\/(\d+)/)
      version = match ? match[1] : 'Unknown'
      supported = true
    } else if (userAgent.includes('Edge')) {
      name = 'Edge'
      const match = userAgent.match(/Edge\/(\d+)/)
      version = match ? match[1] : 'Unknown'
      supported = true
    } else if (userAgent.includes('Firefox')) {
      name = 'Firefox'
      const match = userAgent.match(/Firefox\/(\d+)/)
      version = match ? match[1] : 'Unknown'
      supported = false
    }

    return { name, version, supported }
  }
}

// 网络连接管理器
export class NetworkManager {
  private static instance: NetworkManager | null = null
  private isOnline = true
  private listeners: Array<(online: boolean) => void> = []
  private testCache = { result: false, timestamp: 0 }
  private readonly CACHE_DURATION = 30000 // 30秒缓存

  static getInstance(): NetworkManager {
    if (!this.instance) {
      this.instance = new NetworkManager()
    }
    return this.instance
  }

  constructor() {
    this.init()
  }

  private init(): void {
    if (typeof navigator !== 'undefined' && navigator.onLine !== undefined) {
      this.isOnline = navigator.onLine
      
      window.addEventListener('online', () => {
        this.isOnline = true
        this.notifyListeners(true)
      })
      
      window.addEventListener('offline', () => {
        this.isOnline = false
        this.notifyListeners(false)
      })
    }
  }

  getOnlineStatus(): boolean {
    return this.isOnline
  }

  addListener(callback: (online: boolean) => void): void {
    this.listeners.push(callback)
  }

  removeListener(callback: (online: boolean) => void): void {
    const index = this.listeners.indexOf(callback)
    if (index > -1) {
      this.listeners.splice(index, 1)
    }
  }

  private notifyListeners(online: boolean): void {
    this.listeners.forEach(callback => callback(online))
  }

  // 测试网络连接（带重试机制和多个测试端点）
  async testConnection(retries = 2, timeout = 2000): Promise<boolean> {
    // 首先检查基本的在线状态
    if (typeof navigator !== 'undefined' && !navigator.onLine) {
      console.log('浏览器显示离线状态')
      return false
    }
    
    // 检查缓存，避免频繁的网络请求
    const now = Date.now()
    if (now - this.testCache.timestamp < this.CACHE_DURATION) {
      console.log('使用缓存的网络测试结果')
      return this.testCache.result
    }
    
    // 使用更轻量的测试端点，减少超时时间
    const testUrls = [
      'https://www.google.com/generate_204',
      'https://www.bing.com/favicon.ico'
    ]
    
    for (let i = 0; i < retries; i++) {
      for (const url of testUrls) {
        try {
          const controller = new AbortController()
          const timeoutId = SafeTimer.setTimeout(() => {
            controller.abort()
          }, timeout)
          
          await fetch(url, {
            method: 'HEAD',
            mode: 'no-cors',
            cache: 'no-cache',
            signal: controller.signal
          })
          
          SafeTimer.clearTimeout(timeoutId)
          
          // 缓存成功结果
          this.testCache = { result: true, timestamp: now }
          return true
        } catch (error: any) {
          // 处理特定的网络错误
          if (error.name === 'AbortError') {
            console.log(`网络测试超时: ${url}`)
          } else if (error.message?.includes('ERR_NETWORK_CHANGED')) {
            console.log(`网络状态变化: ${url}`)
            // 网络状态变化时，等待更长时间后重试
            await SafeDelay.delay(2000)
          } else if (error.message?.includes('ERR_INTERNET_DISCONNECTED') || 
                     error.message?.includes('ERR_CONNECTION_TIMED_OUT')) {
            console.log(`网络连接问题: ${url}`)
            // 如果是连接超时或断开，直接返回false，不继续尝试
            this.testCache = { result: false, timestamp: now }
            return false
          } else {
            console.log(`网络测试失败: ${url}`, error.message)
          }
          // 继续尝试下一个URL
          continue
        }
      }
      
      // 如果所有URL都失败，等待后重试（但减少重试次数）
      if (i < retries - 1) {
        await SafeDelay.delay(500) // 减少等待时间
      }
    }
    
    // 缓存失败结果
    this.testCache = { result: false, timestamp: now }
    return false
  }
}
